package com.user.query.service.impl;

import java.util.List;

import javax.annotation.Resource;

import com.user.query.dao.RoleMapper;
import com.user.query.dao.RoleMenuMapper;
import com.user.query.model.Role;
import com.user.query.model.RoleMenu;
import com.user.query.service.RoleService;
import com.user.query.utils.IDGenerator;
import com.user.query.utils.Page;
import com.user.query.vo.RoleVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RoleServiceImpl implements RoleService {
	
	@Autowired
	private RoleMapper roleMapper;
	
	@Resource
	private RoleMenuMapper roleMenuMapper;
	
	@Override
	public Page<Role> queryPage(Page<Role> page) {
		page.setTotalRecord(roleMapper.countByPage(page));
		page.setResults(roleMapper.selectByPage(page));
		return page;
	}

	@Override
	public List<Role> grep(Role role) {
		return roleMapper.selectModel(role);
	}

	@Override
	public Role get(String id) {
		return (Role) roleMapper.selectByPrimaryKey(id);
	}

	@Override
	public void modifyOrAdd(Role role) {
		if(StringUtils.isEmpty(role.getRoleId())) {
			role.setRoleId(IDGenerator.getUUID());
			roleMapper.insert(role);
		}else {
			roleMapper.updateByPrimaryKeySelective(role);
		}
	}

	@Override
	public List<Role> findByLevels(int[] levels) {
		
		return roleMapper.findByLevels(levels);
	}

	@Override
	public void modify(RoleVo role) {
		roleMenuMapper.deleteByRoleId(role.getRoleId());
		for(String menuId:role.getMenuId()) {
			RoleMenu roleMenu = new RoleMenu();
			roleMenu.setMenu(menuId);
			roleMenu.setRole(role.getRoleId());
			roleMenuMapper.insert(roleMenu);
		}
		
		this.modifyOrAdd(role);
	}
}
